package com.hmall.trade.listener;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.trade.Constants.MQConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {
    private final IOrderService orderService;
    private  final PayClient payClient;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name=MQConstants.DELAY_QUEUE_NAME,durable = "true"),
            exchange = @Exchange(name=MQConstants.DELAY_EXCHANGE_NAME,delayed = "true"),
            key= MQConstants.DELAY_ROUTING_KEY
    ))
    public  void listenOrderDelayMessage(Long orderId){
         // 1.查询 订单
        Order order = orderService.getById(orderId);
        if(order ==null || order.getStatus()!=1){
            return ;
        }
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);
        if(payOrderDTO==null || payOrderDTO.getStatus()!=3){
           // 回滚库存
            orderService.canleOrder(orderId);
        }
        else{
            orderService.markOrderPaySuccess(orderId);
        }
    }
}
